package asia.lxq.cic.service;

import asia.lxq.cic.dao.ActivityMapper;
import asia.lxq.cic.dao.AreaMapper;
import asia.lxq.cic.dao.SignMapper;
import asia.lxq.cic.dao.UserMapper;
import asia.lxq.cic.entity.Activity;
import asia.lxq.cic.entity.Result;
import asia.lxq.cic.entity.Sign;
import asia.lxq.cic.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ActivityService {

    @Autowired
    ActivityMapper activityMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    SignMapper signMapper;
    @Autowired
    AreaMapper areaMapper;

    public Activity getActivityById(int activityId){
        Activity activity = activityMapper.selectById(activityId);
        activity.setSponsor(userMapper.selectById(activity.getActivitySponsorId()));
        activity.getSponsor().query(areaMapper);
        QueryWrapper<Sign> innerQuery=new QueryWrapper<>();
        innerQuery.eq("sign_Activity_Id",activity.getActivityId());
        activity.setParticipantList(signMapper.selectList(innerQuery));
        activity.getParticipantList().forEach(sign -> {
            User user = userMapper.selectById(sign.getSignUserId());
            if (user!=null) {
                user.query(areaMapper);
                sign.setUser(user);
            }
        });
        return activity;
    }

    public Sign isSign(int userId,int activityId){
        QueryWrapper<Sign> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("sign_user_id",userId).eq("sign_Activity_Id",activityId);
        return signMapper.selectOne(queryWrapper);
    }

    public Result<Sign> engageActivity(int userId,int activityId,String appealText){
        User user = userMapper.selectById(userId);
        if (user==null)return Result.success(null);
        QueryWrapper<Sign> signQueryWrapper=new QueryWrapper<>();
        signQueryWrapper.eq("sign_User_Id",userId).eq("sign_Activity_Id",activityId);
        Sign selectOne = signMapper.selectOne(signQueryWrapper);
        if (selectOne!=null)Result.success(selectOne);
        Activity activity = activityMapper.selectById(activityId);
        Sign sign;
        if (activity.getActivityExtent().equals("班级")&&activity.getActivityGroupId()==user.getGroupId() ||
                activity.getActivityExtent().equals("全校")&&activity.getActivityCollegeId()==user.getCollegeId() ||
                activity.getActivityExtent().equals("全国")){
            sign=new Sign(0,userId,activityId,null,appealText,null,null,null);
            signMapper.insert(sign);
        } else {
            sign=null;
        }
        return Result.success(sign);
    }

    public Activity addActivity(Activity activity){
        activityMapper.insert(activity);
        signMapper.insert(new Sign(0,activity.getActivitySponsorId(),activity.getActivityId(),
                null,null,null,null,null));
        return activity;
    }

    public Activity alterActivity(Activity activity){
        String activityExtent = activity.getActivityExtent();
        activityMapper.updateById(activity);
        QueryWrapper<Sign> signQueryWrapper=new QueryWrapper<>();
        HashMap<String,Object> queryMap=new HashMap<>();
        if (activityExtent.equals("全校")){
            queryMap.put("sign_Activity_Id",activity.getActivityId());
            List<Sign> signList = signMapper.selectByMap(queryMap);
            signList.forEach(sign -> {
                User user=userMapper.selectById(sign.getSignUserId());
                if (user.getCollegeId()!=activity.getActivityCollegeId())signMapper.deleteById(sign.getSignId());
            });
        }
        if (activityExtent.equals("班级")){
            queryMap.put("sign_Activity_Id",activity.getActivityId());
            List<Sign> signList = signMapper.selectByMap(queryMap);
            signList.forEach(sign -> {
                User user=userMapper.selectById(sign.getSignUserId());
                if (user.getGroupId()!=activity.getActivityGroupId())signMapper.deleteById(sign.getSignId());
            });
        }
        return activity;
    }

    public int deleteActivity(int activityId){
        return activityMapper.deleteById(activityId);
    }

    public Result<Object> getActivityList(int collegeId,int groupId,int page, int pageSize){
        QueryWrapper<Activity> queryWrapper=new QueryWrapper<>();
        if (collegeId<=0) queryWrapper.eq("activity_extent","全国");
        else queryWrapper.eq("activity_college_Id",collegeId);
        if (groupId>0)queryWrapper.eq("activity_group_Id",groupId);
        queryWrapper.orderByDesc("activity_date");
        return resultPage(queryWrapper, page, pageSize);
    }
    public Result<Object> resultPage(QueryWrapper<Activity> queryWrapper,int page, int pageSize){
        Map<String,Object> resultData=new HashMap<>();
        Page<Activity> selectPage = activityMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
        List<Activity> records = selectPage.getRecords();
        records.forEach(activity -> {
            activity.setSponsor(userMapper.selectById(activity.getActivitySponsorId()));
            activity.getSponsor().query(areaMapper);
            QueryWrapper<Sign> innerQuery=new QueryWrapper<>();
            innerQuery.eq("sign_Activity_Id",activity.getActivityId());
            activity.setParticipantList(signMapper.selectList(innerQuery));
            activity.getParticipantList().forEach(sign -> {
                User user = userMapper.selectById(sign.getSignUserId());
                if (user!=null) {
                    user.query(areaMapper);
                    sign.setUser(user);
                }
            });
        });
        resultData.put("data",records);
        resultData.put("total",selectPage.getTotal());
        resultData.put("current",selectPage.getCurrent());
        resultData.put("pages",selectPage.getPages());
        return Result.success(resultData);
    }

    public Result<Object> getOwnActivity(int userId,int page, int pageSize){
        QueryWrapper<Activity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("activity_Sponsor_Id",userId);
        return resultPage(queryWrapper, page, pageSize);
    }

    public Result<Object> getEngageActivity(int userId,int page, int pageSize){
        Map<String,Object> resultData=new HashMap<>();
        QueryWrapper<Sign> signQueryWrapper=new QueryWrapper<>();
        signQueryWrapper.eq("sign_User_Id",userId);
        List<Activity> engageActivityList=new ArrayList<>();
        List<Sign> userSignList = signMapper.selectList(signQueryWrapper);
        if (userSignList==null){
            resultData.put("data",null);
            resultData.put("total",0);
            resultData.put("current",page);
            resultData.put("pages",1);
            return Result.success(resultData);
        }
        int userSignSize=userSignList.size();
        int currentRow=page*pageSize-pageSize;
        for(int i=0;i<=pageSize;i++){
            if (currentRow+i>=userSignSize)break;
            Sign sign = userSignList.get(currentRow + i);
            Activity activity = activityMapper.selectById(sign.getSignActivityId());
            if (activity==null)continue;
            engageActivityList.add(activity);
        }
        engageActivityList.forEach(activity -> {
            activity.setSponsor(userMapper.selectById(activity.getActivitySponsorId()));
            activity.getSponsor().query(areaMapper);
            HashMap<String,Object> columnMap=new HashMap<>();
            columnMap.put("sign_Activity_Id",activity.getActivityId());
            activity.setParticipantList(signMapper.selectByMap(columnMap));
        });
        resultData.put("data",engageActivityList);
        resultData.put("total",userSignSize);
        resultData.put("current",page);
        resultData.put("pages",userSignSize/pageSize==0?1:userSignSize/pageSize);
        return Result.success(resultData);
    }

    public Result<Boolean> isAllow(int activityId, int userId){
        Activity activity=activityMapper.selectById(activityId);
        if (activity==null)return Result.success(false);
        User user = userMapper.selectById(userId);
        if (activity.getActivityExtent().equals("班级")) {
            if (user.getGroupId()==activity.getActivityGroupId())
                return Result.success(true);
            else return Result.success(false);
        } else if (activity.getActivityExtent().equals("全校")) {
            if (user.getCollegeId()==activity.getActivityCollegeId())
                return Result.success(true);
            else return Result.success(false);
        }else return Result.success(true);
    }
}
